package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.ScanTest;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Autowired
    private ScanTest scanTest;
    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    
    @Autowired
    private AdSensitiveService adSensitiveService;


    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer newsId) {
        //1:校验参数
        if(newsId ==null){
            return ;
        }

        //2:根据文章id查询文章对象
        WmNews wmNews = wemediaFeign.findByNewsId(newsId);
        if(wmNews==null){
            return;
        }

        //3:4 人工审核通过  8 审核通过待发布   状态改成9 已发布
        if((wmNews.getStatus()==4 ||wmNews.getStatus()==8 ) && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            this.saveArticle(wmNews);
        }

        //4：待审核
        if(wmNews.getStatus()==1){

            //1:分离文章内容和封面中所有的文本和图片
            Map<String, Object> map = this.handleTextAndImages(wmNews);
            //文章内容+文章标题一块作为文本审核
            String text = map.get("text").toString()+wmNews.getTitle();

            //1审核文本
            /*Map<String, Object> scanText = scanTest.scanText(text);
            JSONObject showapi_res_body =(JSONObject) scanText.get("showapi_res_body");
            String sug = showapi_res_body.get("sug").toString();
            if(!sug.equals("pass")){
                //审核没通过或不确定  block  review  pass
                if(sug.equals("block")){
                    updateWmnewStatus(wmNews,(short)2,"文本包含敏感信息");
                    return;
                }else if(sug.equals("review")){
                    updateWmnewStatus(wmNews,(short)3,"文本审核信息异常转交人工审核");
                    return;
                }

            }

            //2审核图片
            List<String> imageList = (List<String>)map.get("image");
            for(String imageUrl: imageList){

                String groupUrl =imageUrl.replace(fileServerUrl,"");
                String group =groupUrl.substring(0,groupUrl.indexOf("/"));
                String imgPath = groupUrl.replace(group,"").substring(1);
                try {
                    byte[] bytes = fastDFSClient.download(group, imgPath);
                    Map<String, Object> scanImage = scanTest.scanImage(bytes);

                    JSONObject showapi_res_body_img =(JSONObject) scanImage.get("showapi_res_body");
                    String imgSug = showapi_res_body_img.get("sug").toString();
                    if(!imgSug.equals("pass")){
                        //审核没通过或不确定  block  review  pass
                        if(imgSug.equals("block")){
                            updateWmnewStatus(wmNews,(short)2,"图片包含敏感信息");
                            return;
                        }else if(imgSug.equals("review")){
                            updateWmnewStatus(wmNews,(short)3,"图片审核信息异常转交人工审核");
                            return;
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }*/

            //审核敏感词
            boolean b = this.handleSensitive(text);
            if(b){
                updateWmnewStatus(wmNews,(short)2,"图片包含敏感信息");
                return;
            }

            //审核都通过保存文章3个表
            this.saveArticle(wmNews);
        }

    }

    //审核敏感词
    private boolean handleSensitive(String content){
        boolean result =false;
        
        //初始化map集合
        List<String> allSensitive = adSensitiveService.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        
        //开始匹配
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if(stringIntegerMap.size()>0){
            result=true;
        }
        return result;
    }
    

    //分离文章中的文本和图片
    public Map<String,Object>  handleTextAndImages(WmNews wmNews){
        String content = wmNews.getContent();

        List<Map> contentList = JSON.parseArray(content, Map.class);

        StringBuilder stringBuilder =new StringBuilder(); //存所有文本
        List<String> imageList =new ArrayList<>(); //存图片地址

        //内容
        for(Map map:contentList){

            if(map.get("type").equals("text")){
                stringBuilder.append(map.get("value").toString());
            }
            if(map.get("type").equals("image")){
                imageList.add(map.get("value").toString());
            }
        }

        //封面
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] strings = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(strings));
        }

        //封装分离后的结果
        Map<String,Object> map =new HashMap<>();
        map.put("text",stringBuilder);
        map.put("image",imageList);
        return map;
    }

    //跟新文章wmnew 状态
    private void updateWmnewStatus(WmNews wmNews,Short status,String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wemediaFeign.updateNewsStatus(wmNews);
    }

    //保存文章3张表
    private void saveArticle(WmNews wmNews){
        //1：主表 aparticle
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        apArticle.setLabels(wmNews.getLabels());
        apArticle.setPublishTime(wmNews.getPublishTime());

        //查作者  wmnews  userid ---->wmuser  ApAuthorId ----->ApAuthor
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findById(userId);
        if(wmUser!=null){
            ApAuthor apAuthor = articleFeign.findById(wmUser.getApAuthorId());
            if(apAuthor!=null){
                apArticle.setAuthorId(Long.valueOf(apAuthor.getId().toString()));
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        //频道
        AdChannel adChannel = adChannelMapper.selectById(wmNews.getChannelId());
        if(adChannel!=null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }
        ApArticle article = articleFeign.saveApArticle(apArticle);

        //2:保存articleConfig
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(article.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);

        //3:保存articleContent
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(article.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);

        //审核通过的 （发布时间<=当前时间）更新发布成功
        if(wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            this.updateWmnewStatus(wmNews,(short) 9,"发布成功");
            //单条插入到es中

        }else{
            this.updateWmnewStatus(wmNews,(short) 8,"审核通过待发布");
        }

    }
}
